package dev_ops.tools.kafka;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.dev_common.file.FileUtils;
import org.dev_common.json.Jacksons;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Table;
import com.google.common.collect.TreeBasedTable;

public class BizActionTools {
    public static Pattern index_zx_srv_2017_pattern = Pattern.compile("zx-srv-(.*)-2017.[0-9][0-9].[0-9][0-9]");
    public static final List<String> bizTypes = Arrays.asList(
            "yms", 
            "packet", 
            "cm", 
            "ympns", 
            "muc", 
            "muc-server", 
            "webmsg", 
            "user",
            "friend", 
            "contact", 
            "contact-recommend", 
            "rcc", 
            "rcc-report", 
            "recommend-web", 
            "recommend-task",
            "nearby", 
            "link", 
            "pot", 
            "sync");

    public static void main(String[] args) throws Exception {
        // dc数据上报();
        //oooooooooooooooooooooooooooooooooooooooooooo();
        获取bizType_bizAction_以及字段名字();
    }

    /**
     * 映射关系维护: wiki更新地址
     * http://wiki.zenmen.corp/pages/viewpage.action?pageId=15631772
     * 
     * @throws Exception
     */
    public static void dc数据上报() throws Exception {
        Map<String, Set<String>> result = new HashMap<>();
        HttpClient client = HttpClientBuilder.create().build();
        HttpEntity entity = client.execute(new HttpGet("http://10.135.20.38:9200/_mappings")).getEntity();
        String ss = EntityUtils.toString(entity);
        @SuppressWarnings("rawtypes")
        Map<String, Map<String, Map<String, Map>>> obj = Jacksons.parse(ss,
                new TypeReference<Map<String, Map<String, Map<String, Map>>>>() {});
        for (Entry<String, Map<String, Map<String, Map>>> entry : obj.entrySet()) {
            Matcher matcher = index_zx_srv_2017_pattern.matcher(entry.getKey());
            if (matcher.find()) {
                String bizAction = matcher.group(1);
                @SuppressWarnings("rawtypes")
                Map<String, Map<String, Map>> typemap = entry.getValue();
                result.put(bizAction, typemap.get("mappings").keySet());
            }
        }
        List<String> list = bizTypes;
        Map<String, String> define_map = oooooooooooooooooooooooooooooooooooooooooooo();
        for (String bizType : list) {
            boolean print = false;
            //System.out.println(result.get(string).toString().replaceAll("[\\]\\[]", ""));
            String line_3="";
            for (String bizAction : result.get(bizType)) {
                // TODO print as a csv, dont delete belows.
//                String line = "";
//                if (print) {
//                    line +="";
//                }else {
//                    line += bizType;
//                    print = true;
//                }
//                String info = null==define_map.get(bizType+"."+bizAction)
//                        ?"":"["+ define_map.get(bizType+"."+bizAction)+"]";
//                line +=","+bizAction+info;
//                System.out.println(line);
                
                String info = null==define_map.get(bizType+"."+bizAction)
                      ?"":"["+ define_map.get(bizType+"."+bizAction)+"]";
                line_3 += bizAction + info +", ";
            }
            System.out.println(/*bizType + "\t" + */line_3.substring(0, line_3.length()-2));
        }
    }

    static Map<String, String> oooooooooooooooooooooooooooooooooooooooooooo() {
        Map<String, String> map = new HashMap<>(128);
        List<String> lines = FileUtils.listString("/home/thomas/docs");
        for (int i = 0; i < lines.size() - 1; i++) {
            if (lines.get(i).matches("^[0-9]+\\..*")) {
                //System.out.println(lines.get(i) + "--" + lines.get(i + 1));
                
                String key = lines.get(i + 1).replaceAll("[\\u4e00-\\u9fa5]", "").replaceAll(" ", "")
                        .replace("(", "").replace(")", "").replace(".*", "")
                        .replace("：", "").replace(":", "").trim();
                String info = lines.get(i).replaceAll("^[0-9]+\\.", "").trim();
                System.out.println(key + "--" + info);
                map.put(key, info);
            }
        }
        return map;
    }

    private static void 获取bizType_bizAction_以及字段名字() throws Exception {
        Map<String, Set<String>> result = new HashMap<>();
        HttpClient client = HttpClientBuilder.create().build();
        HttpEntity entity = client.execute(new HttpGet("http://10.135.20.38:9200/_mappings")).getEntity();
        String ss = EntityUtils.toString(entity);
        Map<String, Map<String, Map<String, Map>>> obj = Jacksons.parse(ss,
                new TypeReference<Map<String, Map<String, Map<String, Map>>>>() { });
        Table<String, String, Set<Pair<String,String>>> table = TreeBasedTable.create();
        Map<String, Set<Pair<String,String>>> more = new TreeMap<>();
        for (Entry<String, Map<String, Map<String, Map>>> entry : obj.entrySet()) {
            Matcher matcher = index_zx_srv_2017_pattern.matcher(entry.getKey());
            if (matcher.find()) {
                String bizType = matcher.group(1);
                Map<String, Map<String, Map>> typemap = entry.getValue();
                for(Entry<String, Map> bizAction: typemap.get("mappings").entrySet()) {
                    String bizAct = bizAction.getKey();
                    @SuppressWarnings("unchecked")
                    Map<String, Map<String,Map>> propmap = (Map<String, Map<String, Map>>) (bizAction.getValue().get("properties"));
                    Set<Pair<String,String>> set = new TreeSet<>();
                    for (Entry<String, Map<String, Map>> fields : propmap.entrySet()) {
                        String key = fields.getKey();
                        try {
                            Map<String, Map> sss = fields.getValue();
                            Object object = sss.get("type");
                            String right = object.toString();
                            if ("biztype".equalsIgnoreCase(key)||"bizaction".equalsIgnoreCase(key)) {
                                //continue;
                            }else {
                                set.add(new Pair(key, right));
                            }
                            //set.add(new Pair(key, sss.get("type").toString()));
                        } catch (Exception e) {
                            e.printStackTrace();
                            System.err.println(fields.getValue());
                            System.exit(0);
                        }
                    }
                    String indexKey = bizType+"-"+bizAct;
                    System.out.println(indexKey);
                    /*if (table.get(bizType, bizAct)!=null) {
                        // table.get(bizType, bizAct).addAll(set);
                        more.put(key, value)
                    }else {
                        table.put(bizType, bizAct, set);
                    }*/
                    if (more.get(indexKey)!=null) {
                        more.get(indexKey).addAll(set);
                    }else {
                        more.put(indexKey, set);
                    }
                }
            }
        }
        String ohmygod = "";
        ohmygod +="index,bizType,bizAction,字段名,ES中类型\n";
        int index = 1;
        for (Entry<String, Set<Pair<String, String>>> biztype : more.entrySet()) {
            ohmygod += "" + (index++) + "," + biztype.getKey().split("-")[0] + "," + biztype.getKey().split("-")[1] + ",,\n";
            for (Pair<String, String> col : biztype.getValue()) {
                ohmygod+= ",,,"+ col.l +"," + col.r+"\n";
            }
        }
        FileUtils.file(ohmygod,"bizType_bizAction_and_their_properties.csv");
    }
}
class Pair<L extends Comparable<L>,R> implements Comparable<Pair<L,R>>{
    public R r;
    public L l ;
    public Pair(L l, R r) {
        this.r = r;
        this.l = l;
    }
    @Override
    public boolean equals(Object obj) {
        return l.equals(((Pair)obj).l);
    }
    @Override
    public String toString() {
        return "("+l+","+r+")";
    }
    @Override
    public int compareTo(Pair<L, R> o) {
        return l.compareTo(o.l);
    }
}
